﻿using Admin.NET.Core.Btms;
using DocumentFormat.OpenXml.Office.CustomUI;
using Furion.DatabaseAccessor;
using Yitter.IdGenerator;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.NontaxInsertBillRequest.Types.CardExtra.Types.BillCard.Types;

namespace Admin.NET.Application.Service;
public class InvTuiXueService : BaseServiceBill<InvTuiXue>
{
    private readonly SqlSugarRepository<InvTuiXueMingXi> _repMingXi;
    private readonly SqlSugarRepository<InvKuCun> _kuCun;
    private readonly SqlSugarRepository<InvBloodInfo> _btms2BloodInfo;
    private readonly SqlSugarRepository<InvStockInBillMaster> _btms2StockInMaster;
    private readonly SqlSugarRepository<InvStockInBillDetail> _btms2StockInDetail;


    public InvTuiXueService(IServiceScopeFactory scopeFactory, 
        SqlSugarRepository<InvTuiXueMingXi> repMingXi,
        SqlSugarRepository<InvKuCun> kuCun,
        SqlSugarRepository<InvBloodInfo> btms2BloodInfo,
        SqlSugarRepository<InvStockInBillMaster> btms2StockInMaster,
        SqlSugarRepository<InvStockInBillDetail> btms2StockInDetail) : base(scopeFactory)
    {
        _repMingXi = repMingXi;
        _kuCun = kuCun;
        _btms2BloodInfo = btms2BloodInfo;
        _btms2StockInMaster = btms2StockInMaster;
        _btms2StockInDetail = btms2StockInDetail;
    }
    /// <summary>
    /// 获取列表
    /// </summary>
    [AllowAnonymous]
    public async Task<SqlSugarPagedList<InvTuiXueOutput>> Page(InvTuiXuePageInput input)
    {
        var invKuCunList = await Queryable.FuzzyQuery(input.Keyword, new List<string> { "Id" })
           .WhereIF(input.StartTime.HasValue, t => t.CreateTime >= input.StartTime)
           .WhereIF(input.EndTime.HasValue, t => t.CreateTime <= input.EndTime)
           .WhereIF(input.danJuZhuangTai.HasValue(), t => t.danJuZhuangTai == input.danJuZhuangTai)
           .Select<InvTuiXueOutput>()
           .OrderByDescending(it => it.Id)
           .ToPagedListAsync(input.Page, input.PageSize);

        return invKuCunList;
    }
    [AllowAnonymous]
    public async Task<InvTuiXueZhuCongOutput> Get(string id)
    {
        var zhuBiao = GetById<InvTuiXueOutput>(id);

        // 直接联查明细表和库存表
        var mingXiList = await _repMingXi.Queryable
            .Includes(t => t.xueYe) // 联查库存表
            .Where(t => t.invTuiXueId == id)
            .ToListAsync()
            .ContinueWith(t => t.Result.Adapt<List<InvTuiXueMingXiOutput>>());

        return new InvTuiXueZhuCongOutput
        {
            zhuBiao = zhuBiao,
            mingXiList = mingXiList
        };
    }
    [UnitOfWork]
    public string Add(InvTuiXueAddInput input)
    {
        input.danJuZhuangTai = DanJuZhuangTai.已生效;
        // 入库单单号
        var billNo = YitIdHelper.NextId().ToString();
        input.tuiXueRuKuDanHao = billNo;
        // 插入主表
        var zhuBiao = AddWithInput(input);

        // 明细表添加主表id
        foreach (var item in input.mingXiList)
        {
            item.invTuiXueId = zhuBiao.Id; // 主表Id
        }
        _repMingXi.InsertRange(input.mingXiList);
        // 获取血液信息
        var xueYeIdList = input.mingXiList.Select(t => t.xueYeId).ToList();
        var btms3BloodList = _kuCun.Queryable.Where(t => xueYeIdList.Contains(t.Id)).ToList();
        // 更新血液库存状态
        foreach(var item in btms3BloodList)
        {
            item.kuCunZhuangTai = KuCunZhuangTai.已出库;
            item.remark = "协议医院退血";
        }
        _kuCun.AsUpdateable(btms3BloodList).UpdateColumns(it => new { it.UpdateTime, it.UpdateUserId, it.UpdateUserName, it.kuCunZhuangTai, it.remark }).ExecuteCommand();
        // 获取血库2的库存信息
        var btms3BloodCodeList = btms3BloodList.Select(t => t.xianXueMa + t.chanPinId).ToList();
        var btms2BloodInfoList = _btms2BloodInfo.Queryable.Where(t => btms3BloodCodeList.Contains(t.Code)).ToList();
        // 插入血库2入库表
        _btms2StockInMaster.Insert(new InvStockInBillMaster
        {
            BillNo = billNo,
            BillType = "XieYiYiYuanTuiXue",
            BillStatus = 0,
            CreationTime = DateTime.Now,
            CreatorUserId = 2,
            BusinessType = 1,
            BasBloodSourceId = input.tuiXueYiYuan,
            SourceBillNo = zhuBiao.Id,
            SumQty = btms2BloodInfoList.Count,
            Remark = input.tuiXueYuanYin
        });
        List<InvStockInBillDetail> detailList = new List<InvStockInBillDetail>();
        foreach(var item in btms2BloodInfoList)
        {
            var detail = item.Adapt<InvStockInBillDetail>();
            detail.CreationTime = DateTime.Now;
            detail.CreatorUserId = 2;
            detail.IsDeleted = false;
            detail.BillNo = billNo;
            detailList.Add(detail);
        }
        _btms2StockInDetail.InsertRange(detailList);
        return zhuBiao.Id;
    }

}
